package com.ourteam.workspace.api;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

import com.ourteam.frame.util.RelativeDateFormat;
import com.ourteam.frame.web.AbstractTreeNodeBuilder;
import com.ourteam.scm.utils.VersionInfo;
import com.ourteam.workspace.service.IWorkspaceService;
import com.ourteam.workspace.service.WorkspaceServiceFactory;

public abstract class AbstractWorkspaceResourceTreeNodeBuilder<ParentObject> extends
		AbstractTreeNodeBuilder<ParentObject, WorkspaceResourceFileBean> implements IWorkspaceResourceNodeBuilder {

	private File workspaceRootDir;

	protected static final IWorkspaceService workspaceService = WorkspaceServiceFactory.getWorkspaceService();

	public void setWorkspaceRootDir(File workspaceRootDir) {
		this.workspaceRootDir = workspaceRootDir;
	}

	public File getWorkspaceRootDir() {
		return workspaceRootDir;
	}

	@Override
	public Object getNodeId(WorkspaceResourceFileBean childObject) throws Exception {
		return childObject.getId();
	}

	@Override
	public boolean isLeaf(WorkspaceResourceFileBean childObject) throws Exception {
		if (childObject.getResourceFile().isFile()) {
			return true;
		} else {
			return false;
		}
	}

	public String getTag(WorkspaceResourceFileBean childObject) throws Exception {
		if (childObject.getResourceFile().isDirectory()) {
			return null;
		}
		VersionInfo versionInfo = childObject.getVersionInfo();
		if (versionInfo != null) {
			List<String> tags = new ArrayList<String>();
			tags.add(versionInfo.getRevision());
			if (StringUtils.isNotBlank(versionInfo.getLastCommitAuthor())) {
				tags.add(versionInfo.getLastCommitAuthor());
			}
			if(versionInfo.getTimestamp() != null){
				tags.add(RelativeDateFormat.format(versionInfo.getTimestamp()));
			}
			return StringUtils.join(tags, " - ");
		} else {
			return null;
		}

	}

	@Override
	public int getChildCount(WorkspaceResourceFileBean childObject) throws Exception {
		if (childObject.getResourceFile().isFile()) {
			return 0;
		} else {
			return ArrayUtils.getLength(childObject.getResourceFile().list());
		}

	}

	@Override
	public String getNodeDefineId(WorkspaceResourceFileBean childObject) throws Exception {
		if (childObject.getResourceFile().isDirectory()) {
			return "folderNode";
		} else {
			return "fileNode";
		}
	}

}
